package com.qingcheng.filter;

import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gongxiaodian
 * @Date 2019/7/26 18:37
 */

/**
 * 敏感词汇过滤器
 */

public class SensitiveWordsFilter implements Filter {

    /**
     * 储存敏感词汇
     */
    private List<String> list=new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String realPath = servletContext.getRealPath("/sensitiveWords.txt");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "UTF-8"));
            String line = null;
            while ((line=br.readLine())!=null){
                list.add(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void doFilter(final ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        ServletRequest proxy_request = (ServletRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("getParameterValues")){
                    String[] value = (String[]) method.invoke(request, args);
                    if (value!=null){
                        for (int i = 0; i < value.length; i++) {
                            for (String s : list) {
                                if (value[i].contains(s)){
                                    value[i]=value[i].replace(s,"***");
                                }
                            }
                        }
                    }
                    return value;
                }
                return method.invoke(request,args);
            }
        });

        chain.doFilter(proxy_request,response);

    }

    @Override
    public void destroy() {

    }
}
